package cn.com.ucap.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;


/**
 * jsoup
 * 
 * @author Macro
 * 
 */
public class JsoupUtil {
	
	private final static String propFile = "/jsoup.properties";
	
	public static String JSOUP_OUTPATH_HTML;
	public static String APP_BASE_PATH ;
	
	//读取配置
	static {
	    Properties prop = new Properties();
	    try{
	        prop.load(JsoupUtil.class.getResourceAsStream(propFile));
	        JSOUP_OUTPATH_HTML = prop.getProperty("jsoup.outphtml.path");
	        APP_BASE_PATH = prop.getProperty("jsoup.app.basepath");
	    }
	    catch(FileNotFoundException e){
	        e.printStackTrace();
	        System.out.println("properties file can not be found!");
	    }
	    catch(IOException e){
	        e.printStackTrace();
	    }
	}
	
	public static void main(String[] args) {
		try {
			createHtml("http://192.168.1.101/snapp/symyzj.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void createHtml(String url) throws IOException {
		String outPath = "";
		String outDir = "";
		if(StringUtil.nullOrEmptyTirm(url)){
			return;
		}
		Document doc = Jsoup.connect(url).timeout(5000).get();
		Elements elements = doc.getElementsByTag("head");
		if(null!=elements && elements.size()>0){
			elements.get(0).appendElement("meta").attr("http-equiv", "Content-Type").attr("content", "text/html; charset=utf-8");
		}
		//截取URL
		if(url.indexOf("/app/")!=-1){
			outPath = url.substring(url.indexOf("/app/")+5);
			if(outPath.indexOf(".jsp")!=-1){
				outPath = outPath.substring(0, outPath.indexOf(".jsp"));
			}else if(outPath.indexOf("?")!=-1){
				outPath = outPath.substring(0, outPath.indexOf("?"));
			}
			
		}
//		System.out.println(url);
//		System.out.println(outPath);
		System.out.println(doc.html());
		if(outPath.indexOf("/")!=-1){
			outDir = outPath.substring(0, outPath.lastIndexOf("/"));
		}
		System.out.println(outDir);
		File fileDir = new File(JSOUP_OUTPATH_HTML+outDir);
		if(!fileDir.exists()){
			fileDir.mkdirs();
		}
		File file = new File(JSOUP_OUTPATH_HTML+outPath+".html");
		try {
			OutputStreamWriter osw = new OutputStreamWriter(
					new FileOutputStream(file, false), "UTF-8");
			osw.write(doc.html());
			osw.flush();
			osw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
